<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="listQuery.content" size="mini" placeholder="关键词" style="width: 200px;"
                class="filter-item" @keyup.enter.native="handleFilter" />

            <el-button v-waves class="filter-item" size="mini" type="primary" icon="el-icon-search"
                style="margin-left:5px;" @click="handleFilter">
                查询
            </el-button>
            <el-button class="filter-item" size="mini" style="margin-left: 10px;" type="primary" icon="el-icon-upload2"
                @click="handleCreate">
                导入话术本
            </el-button>
            <el-button class="filter-item" size="mini" style="margin-left: 10px;" type="primary"
                icon="el-icon-document-delete" @click="alltypes">
                批量删除
            </el-button>
        </div>
        <el-table :key="tableKey" v-loading="listLoading" ref="multipleTable" @selection-change="handleSelectionChange"
            :data="list" border fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80"
                :class-name="getSortClass('id')">
                <template slot-scope="{row}">
                    <span>{{ row.id }}</span>
                </template>
            </el-table-column>
            <el-table-column label="内容" width="350px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.content }}</span>
                </template>
            </el-table-column>

            <el-table-column label="创建时间" width="300px" align="center">
                <template slot-scope="{row}">
                    <el-tag>{{ row.times | parseTime('{y}-{m}-{d} {h}:{i}') }} </el-tag>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
                <template slot-scope="{row,$index}">
                    <el-button size="mini" type="primary" @click="handleUpdate(row, $index)">
                        编辑
                    </el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(row, $index)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px">
                <el-form-item label="话术" label-width="100px">
                    <el-input type="textarea" :autosize="{ minRows: 12, maxRows: 14 }" placeholder="请输入内容每行一条话术"
                        v-model="temp.content">
                    </el-input>
                </el-form-item>
                <!-- <el-form-item label="导入话术本" label-width="100px">
                    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
                    导入文本
                </el-button>
            </div>
        </el-dialog>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="editFormVisible">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px"
                style="width: 400px; margin-left:50px;">

                <el-form-item label="话术" label-width="60px">
                    <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="temp.content">
                    </el-input>

                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
                    修改
                </el-button>
            </div>
        </el-dialog>


    </div>
</template>

<script>
import {
    fetchList, updateArticle,
    getDel, jcList, getListAll, getImplode
} from '@/api/hs'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import UploadExcelComponent from '@/components/UploadExcel/maxindex.vue'
const statusOptions = [
    { key: 1, display_name: '正常' },
    { key: 2, display_name: '暂停' },
    { key: 3, display_name: '封禁' },
    { key: 4, display_name: '异常' }
]
export default {
    name: 'ComplexTable',
    components: { Pagination, UploadExcelComponent },
    directives: { waves },
    filters: {
        statusFilter(status) {
            const statusMap = {
                1: 'success',
                2: 'info',
                3: 'danger'
            }
            return statusMap[status]
        },
        typeFilter(type) {
            return calendarTypeKeyValue[type]
        }
    },
    data() {
        return {
            tableKey: 0,
            list: null,
            listAll: null,
            total: 0,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 20,
                content: '',
            },
            statusOptions,
            jcOptions: [],
            multipleSelection: [],
            showReviewer: false,
            temp: {
                id: undefined,
                content: '',
            },
            dialogFormVisible: false,
            editFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: 'Edit',
                create: '导入话书本'
            },
            pvData: [],
            rules: {
                type: [{ required: true, message: 'type is required', trigger: 'change' }],
                title: [{ required: true, message: 'title is required', trigger: 'blur' }]
            },
            downloadLoading: false
        }
    },
    created() {
        this.getList()
    },
    methods: {
        //批量删除
        alltypes() {
            let list = this.multipleSelection
            let arr = []
            list.forEach(function (item, index) {
                console.log(item); //输出数组的每一个元素
                if (item.logonstatus != 2) {
                    arr.push(item.id)
                }
            });
            if (arr.length > 0) {
                //进行登陆操作
                let temp = {
                    ids: arr.join(",")
                }
                this.listLoading = true
                getDel(temp).then(response => {
                    this.$notify({
                        title: 'Success',
                        message: 'Created Successfully',
                        type: 'success',
                        duration: 2000
                    })
                    this.getList();
                })
            }
        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log('导入数据', this.multipleSelection)
        },

        getJcList() {
            jcList().then(response => {
                console.log(response.data)
                this.jcOptions = response.data.list
            })
        },
        beforeUpload(file) {
            const isLt1M = file.size / 1024 / 1024 < 1
            if (isLt1M) {
                return true
            }
            this.$message({
                message: 'Please do not upload files larger than 1m in size.',
                type: 'warning'
            })
            return false
        },
        handleSuccess({ results, header }) {
            console.log(results)
            console.log(header)
            let listall = {
                dataall: results
            }
            getImplode(listall).then(response => {
                this.dialogFormVisible = false
                this.getList()
            })

        },
        getListAlls() {
            getListAll({ status: 2 }).then(response => {
                this.listAll = response.data.list
            })
        },
        getList() {
            this.listLoading = true
            fetchList(this.listQuery).then(response => {
                console.log(response.data)
                this.list = response.data.list
                this.total = response.data.count
                setTimeout(() => {
                    this.listLoading = false
                }, 1.5 * 1000)
            })
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        handleModifyStatus(row, status) {
            this.$message({
                message: '操作Success',
                type: 'success'
            })
            row.status = status
        },
        sortChange(data) {
            const { prop, order } = data
            if (prop === 'id') {
                this.sortByID(order)
            }
        },
        sortByID(order) {
            if (order === 'ascending') {
                this.listQuery.sort = '+id'
            } else {
                this.listQuery.sort = '-id'
            }
            this.handleFilter()
        },
        resetTemp() {
            this.temp = {
                id: undefined,
                name: '',
                status: 1,
            }
        },
        handleCreate() {
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        createData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    getImplode(this.temp).then(response => {
                        this.dialogFormVisible = false
                        this.$notify({
                            title: 'Success',
                            message: 'Created Successfully',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList()
                    })
                }
            })
        },
        handleUpdate(row) {
            this.temp = Object.assign({}, row) // copy obj
            this.dialogStatus = 'update'
            this.editFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        updateData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    const tempData = Object.assign({}, this.temp)
                    updateArticle(tempData).then(() => {
                        // const index = this.list.findIndex(v => v.id === this.temp.id)
                        // this.list.splice(index, 1, this.temp)
                        this.editFormVisible = false
                        this.$notify({
                            title: 'Success',
                            message: 'Update Successfully',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList()
                    })
                }
            })
        },
        handleDelete(row, index) {
            let temp = {
                id: row.id
            }
            getDel(temp).then(() => {
                this.$notify({
                    title: 'Success',
                    message: 'Created Successfully',
                    type: 'success',
                    duration: 2000
                })
            })
            this.list.splice(index, 1)
        },
        formatJson(filterVal) {
            return this.listAll.map(v => filterVal.map(j => {
                return v[j]
            }))
        },



        getSortClass: function (key) {
            const sort = this.listQuery.sort
            return sort === `+${key}` ? 'ascending' : 'descending'
        }
    }
}
</script>
